//
// Created by mzzmg on 2024/12/13.
//

#include "storage.h"
// storage.c
#include <stdio.h>
#include <string.h>

// 全局变量
static ParkingRecord records[MAX_RECORDS];
static int record_count = 0;

// 初始化存储
void init_storage()
{
    for (int i = 0; i < MAX_RECORDS; i++)
    {
        records[i].is_occupied = false;
    }
    record_count = 0;
}

// 添加停车记录
int add_parking_record(const char *plate, time_t entry_time, int parking_slot)
{
    if (record_count >= MAX_RECORDS)
    {
        return -1; // 存储已满
    }

    for (int i = 0; i < MAX_RECORDS; i++)
    {
        if (!records[i].is_occupied)
        {
            strncpy(records[i].plate_number, plate, sizeof(records[i].plate_number) - 1);
            records[i].plate_number[sizeof(records[i].plate_number) - 1] = '\0';
            records[i].entry_time = entry_time;
            records[i].parking_slot = parking_slot;
            records[i].is_occupied = true;
            records[i].exit_time = 0;
            records[i].parking_fee = 0.0;
            record_count++;
            return 0; // 成功
        }
    }

    return -1; // 未找到可用空间
}

// 更新停车记录
int update_parking_record(const char *plate, time_t exit_time, double parking_fee)
{
    ParkingRecord *record = find_record_by_plate(plate);
    if (record == NULL)
    {
        return -1; // 未找到记录
    }

    record->exit_time = exit_time;
    record->parking_fee = parking_fee;
    record->is_occupied = false;
    record_count--;
    return 0; // 成功
}

// 显示所有停车记录
void display_parking_records()
{
    printf("\n当前停车记录:\n");
    printf("%-10s %-20s %-20s %-10s %-10s\n", "车牌号", "进入时间", "离开时间", "车位", "费用");
    for (int i = 0; i < MAX_RECORDS; i++)
    {
        if (records[i].is_occupied || records[i].exit_time > 0)
        {
            char entry_time_str[20], exit_time_str[20];
            strftime(entry_time_str, sizeof(entry_time_str), "%Y-%m-%d %H:%M:%S", localtime(&records[i].entry_time));
            if (records[i].exit_time > 0)
            {
                strftime(exit_time_str, sizeof(exit_time_str), "%Y-%m-%d %H:%M:%S", localtime(&records[i].exit_time));
            } else
            {
                strcpy(exit_time_str, "--");
            }

            printf("%-10s %-20s %-20s %-10d %-10.2f\n",
                   records[i].plate_number,
                   entry_time_str,
                   exit_time_str,
                   records[i].parking_slot,
                   records[i].parking_fee);
        }
    }
}

// 根据车牌号查找记录
ParkingRecord *find_record_by_plate(const char *plate)
{
    for (int i = 0; i < MAX_RECORDS; i++)
    {
        if (records[i].is_occupied && strcmp(records[i].plate_number, plate) == 0)
        {
            return &records[i];
        }
    }
    return NULL; // 未找到
}